package com.comboo.example.web.applicationService;

import com.comboo.example.domain.Person;
import com.comboo.example.service.PersonService;
import com.comboo.example.web.command.PersonCreateCommand;
import com.comboo.example.web.command.PersonUpdateCommand;
import com.comboo.example.web.exception.ErrorType;
import com.comboo.example.web.exception.ServiceException;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Sherman
 * created in 2018/12/19 2018
 */
@Service
public class PersonApplicationService {

    private final PersonService personService;

    public PersonApplicationService(PersonService personService) {
        this.personService = personService;
    }

    @Transactional(readOnly = true)
    public Person get(Long id) {
        return personService.findById(id);
    }

    @Transactional
    public Person create(PersonCreateCommand command) {
        Person person = new Person();
        BeanUtils.copyProperties(command, person);
        return personService.save(person);
    }

    @Transactional
    public Page<Person> findPage(Pageable pageable) {
        Page<Person> personPage = personService.findPage(pageable);
        System.out.println(personPage.getContent());
        return personPage;
    }

    @Transactional
    public Person update(PersonUpdateCommand command) {
        Person person = personService.findById(command.getId());
        if (person == null) {
            throw new ServiceException(ErrorType.DATA_ACCESS_ERROR);
        }
        BeanUtils.copyProperties(command, person);
        return personService.save(person);
    }

    @Transactional
    public void delete(Long id) {
        personService.deleteById(id);
    }
}
